#include <stdio.h>
#include "app/ApplicationConfig.h"
#include "util/exceptions/Exception.h"
#include "util/exceptions/ElementNotFoundException.h"
#include "util/logger/LoggerManager.h"
#include "util/logger/ConsoleLogger.h"
#include "util/logger/FileLogger.h"
#include "util/StringUtils.h"

namespace util {

LoggerManager* LoggerManager::INSTANCE = NULL;

LoggerManager* LoggerManager::getInstance() {
	if (INSTANCE == NULL) {
		INSTANCE = new LoggerManager(false);
	}
	return INSTANCE;
}

LoggerManager* LoggerManager::getInstanceConfigSafe() {
	if (INSTANCE == NULL) {
		INSTANCE = new LoggerManager(true);
	}
	return INSTANCE;
}
LoggerManager::~LoggerManager() {
	INSTANCE = NULL;
}

LoggerManager::LoggerManager(bool onErrorBuildDefaultConsole) {
	try {
		std::string logType = app::ApplicationConfig::getProperty("loggerType");
		if (logType.compare("console") == 0) {
			this->logger = new ConsoleLogger();
		} else if (logType.compare("file") == 0) {
			std::string logFileName =
					app::ApplicationConfig::getProperty("logFileName");
			std::string errorFileName = app::ApplicationConfig::getProperty(
					"errorFileName");
			this->logger = new FileLogger(logFileName, errorFileName);
		} else {
			throw(Exception("Valor para loggerType invalido."));
		}
	} catch (Exception &e) {
		printf("%s\n", e.getMessage().c_str());
		if (onErrorBuildDefaultConsole) {
			printf("Se utilizara por defecto el logger a consola.\n");
			this->logger = new ConsoleLogger();
		}
	}
}

Logger* LoggerManager::getLogger() {
	return this->logger;
}

}
